package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 该对象需要提供输出的核心方法
 * 1.静态资源html
 */
public class Response {
    private OutputStream outputStream;
    public Response(){}
    public Response(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    /**
     *
     * @param path 就是请求的url 根据url获取到资源的绝对路径，进一步根据绝对路径读取该静态资源文件，
     *             最终通过输出流输出
     */
    public void outputHtml(String path) throws IOException {
        //绝对路径
        String absoluteRsourcePath = StaticResourceUtil.getAbsolutePath(path);
        //输出静态资源文件
        File file = new File(absoluteRsourcePath);
        if(file.exists() && file.isFile()){
            //文件存在才输出
            StaticResourceUtil.outputStaticResouce(new FileInputStream(file),this.outputStream);
        }else{
            //输出404
            String httpHeader404 = HttpProtocolUtil.getHttpHeader404();
            this.output(httpHeader404);
        }
    }

    /**
     * 输出指定字符串
     * @param str
     */
    public void output(String str) throws IOException {
        this.outputStream.write(str.getBytes());
    }
}
